package org.wishwork.api.aftersale.receive.query;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.stock.other.query.OtherInOutQueryRequest;
import org.wishwork.api.stock.other.query.response.OtherInOutQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 实际收货查询
 * @author: WangYX
 * @create: 2022-04-12 15:31
 * @Version: 1.0.0
 **/

public class AfterSaleReceivedQueryApi extends Api<List<AfterSaleReceivedQueryResponse>, AfterSaleReceivedQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(AfterSaleReceivedQueryApi.class);

    private Context context;

    public AfterSaleReceivedQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(AfterSaleReceivedQueryRequest afterSaleReceivedQueryRequest) throws Exception {
        String url = "/open/aftersale/received/query";
        Map<String, Object> params = new HashMap<>();
        if (afterSaleReceivedQueryRequest.getSoIds() != null && afterSaleReceivedQueryRequest.getSoIds().size() > 0) {
            params.put("so_ids", afterSaleReceivedQueryRequest.getSoIds());
        }
        if (afterSaleReceivedQueryRequest.getOIds() != null && afterSaleReceivedQueryRequest.getOIds().size() > 0) {
            params.put("o_ids", afterSaleReceivedQueryRequest.getOIds());
        }
        if (StrUtil.isNotEmpty(afterSaleReceivedQueryRequest.getShopId())) {
            params.put("shop_id", afterSaleReceivedQueryRequest.getShopId());
        }
        if (afterSaleReceivedQueryRequest.getDateType() != null) {
            params.put("date_type", afterSaleReceivedQueryRequest.getDateType());
        }
        return HttpHelper.sendRequest(afterSaleReceivedQueryRequest, params, url);
    }

    @Override
    protected List<AfterSaleReceivedQueryResponse> process(JSONObject data, AfterSaleReceivedQueryRequest afterSaleReceivedQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<AfterSaleReceivedQueryResponse> afterSaleReceivedQueryResponses = datas.toJavaList(AfterSaleReceivedQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = afterSaleReceivedQueryRequest.getPageIndex();
            AfterSaleReceivedQueryRequest build = afterSaleReceivedQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<AfterSaleReceivedQueryResponse> business = business(build);
            afterSaleReceivedQueryResponses.addAll(business);
        }
        return afterSaleReceivedQueryResponses;
    }
}
